﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

namespace LTHD_Web.RSS
{
    public class ItemClassDAO
    {
        public static List<ItemClass> getFeeds(string url)
        {
            List<ItemClass> dsItem = new List<ItemClass>();
            XmlDocument tl = new XmlDocument();
            try
            {
                tl.Load(url);
            }
            catch
            {
                return null;
            }
            try
            {
                XmlNodeList nodeList = tl.SelectNodes("//item");
                int i = 0;
                foreach (XmlNode node in nodeList)
                {
                    i++;
                    ItemClass item = new ItemClass();
                    for (int n = 0; n < node.ChildNodes.Count; n++)
                    {
                        if (node.ChildNodes[n].Name == "title")
                        {
                            XmlNode title = node.ChildNodes[n];
                            item.Title = title.InnerText;
                        }
                        if (node.ChildNodes[n].Name == "description")
                        {
                            XmlNode title = node.ChildNodes[n];
                            item.Description = title.InnerText;
                        }
                        if (node.ChildNodes[n].Name == "link")
                        {
                            XmlNode link = node.ChildNodes[n];
                            item.Link = link.InnerText;
                        }
                        if (node.ChildNodes[n].Name == "pubDate")
                        {
                            XmlNode title = node.ChildNodes[n];
                            DateTime pubDate = DateTime.Parse(title.InnerText);
                            item.PubDate = pubDate.AddHours(-7);
                        }
                    }
                    dsItem.Add(item);
                }
            }
            catch (Exception ex)
            {
                dsItem = null;
            }
            return dsItem;
        }
        public static List<ItemClass> sortByDate(List<ItemClass> listItems)
        {
            int n = listItems.Count;
            if (n == 0 || n == 1)
                return listItems;
            if (n >= 2)
            {
                ItemClass itemTemp = new ItemClass();
                for (int i = 0; i < n - 1; i++)
                    for (int j = i + 1; j < n; j++)
                    {
                        if (listItems[i].PubDate < listItems[j].PubDate)
                        {
                            itemTemp = listItems[i];
                            listItems[i] = listItems[j];
                            listItems[j] = itemTemp;
                        }
                    }
            }
            return listItems;
        }
    }
}